<?php
class NICED_Exception extends Exception 
{
    const CODE_SERVER_ERROR       = 500;

	protected $errorMessage = NULL;
	protected $errorCode    = NULL;
    protected $params       = array();

    protected static $exceptions   = array(
        self::CODE_SERVER_ERROR => "internal server error",       
    );

	public function __construct($message = NULL, $code = NULL, $params = array()) 
	{
        $code = (int)$code;
		$this->errorMessage = $message;
		$this->errorCode    = $code;

        if (is_array($params))
        {
            $this->params       = $params;
        }
        else
        {
            $this->setFriendlyMessage($params);
        }
        $this->log();

		parent::__construct($message, $code);
	}

    public function getErrorCode()
    {
        return $this->errorCode;
    }

    public function getErrorMessage()
    {
        return $this->errorMessage;
    }


    public function getParams()
    {
        return $this->params;
    }

    public function getFriendlyMessage()
    {
        return isset($this->params["friendly_message"]) ? $this->params["friendly_message"] : NULL;
    }

    public function setFriendlyMessage($msg)
    {
        $this->params["friendly_message"] = $msg;
    }

    public static function getErrorMessgeByErrorCode($code)
    {
        return isset(self::$exceptions[$code]) ? self::$exceptions[$code] : NULL;
    }

    public function log()
    {
        NICED_LOG(SC::get("board_config.niced_log_level"), NICED." Exception: ".$this->errorMessage." ".$this->errorCode);
    }

}

class NICED_ValidationException extends NICED_Exception 
{
}

class NICED_DatabaseException extends NICED_Exception 
{
}

class NICED_NotExistsException extends NICED_Exception 
{
}


/**
 * this file is for exception handler
 *
 * exceptionhandler class handle exception, can used by other class
 * @date 2012.6.19
 * @author qixiaona@gmail.com
 * @access public
 * @package NICED 
 * @source NICED opensource php framework
 *
 */
class NICED_ExceptionHandler
{
	private $instance;
    private $throw = true;
    private $exceptions = array();

    public function handle($e)
    {
        if ($this->throw)
        {
            throw $e;
        }
        else
        {
            $this->exceptions[] = $e;
        }
    }

	public function show($e)
	{
		$this->setThrow(true);
		$this->handle($e);
	}

	public function hide($e)
	{
		$this->setThrow(false);
		$this->handle($e);
		$this->setThrow(true);
	}

    public function getExceptions()
    {
        return $this->exceptions;
    }

    public function setThrow($bool)
    {
        $this->throw = $bool;
    }
	
	public function getInstance()
	{
		if (!self::$instance)
		{
			self::$instance = new self();
		}
		
		return self::$instance;
	}
}//end class
